import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import '../models/chat_message.dart';
class ChatHistory {
  final String characterId;
  final String characterName;
  final String characterDescription;
  final String characterImageUrl;
  final List<ChatMessage> messages;

  ChatHistory({
    required this.characterId,
    required this.characterName,
    required this.characterDescription,
    required this.characterImageUrl,
    required this.messages,
  });

  factory ChatHistory.fromJson(Map<String, dynamic> json) {
    return ChatHistory(
      characterId: json['characterId'],
      characterName: json['characterName'],
      characterDescription: json['characterDescription'],
      characterImageUrl: json['characterImageUrl'],
      messages: (json['messages'] as List)
          .map((msg) => ChatMessage.fromJson(msg))
          .toList(),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'characterId': characterId,
      'characterName': characterName,
      'characterDescription': characterDescription,
      'characterImageUrl': characterImageUrl,
      'messages': messages.map((msg) => msg.toJson()).toList(),
    };
  }
}

class ChatService {
  static const String _baseUrl = 'aHR0cHM6Ly9hcGkua2tzai5vcmcvdjEvY2hhdC9jb21wbGV0aW9ucw==';
  static const String _apiKey = 'c2stYjFXVmoxWURiQ2piVzRzSXI1M0tBNVhjbzl1OXFyeTQycnQ5M0dlQ3VtdE9aeGY1';

  get url => deCode(_baseUrl);
  get key => deCode(_apiKey);

  static const String _storageKey = 'chat_history_';
  final SharedPreferences _prefs;

  ChatService(this._prefs);

  static deCode(String s) {
    final bytes = base64.decode(s);
    return utf8.decode(bytes);
  }

  Future<String> sendMessage(
    String characterId, 
    String message, {
    required String characterName,
    required String characterDescription,
    String? characterPersonality,
  }) async {
    final DateTime startTime = DateTime.now();
    print('开始发送消息 - 时间: ${startTime.toIso8601String()}');
    print('角色ID: $characterId');
    print('消息内容: $message');
    
    try {
      print('准备发送HTTP请求...');
      final response = await http.post(
        Uri.parse(url),
        headers: {
          'Authorization': 'Bearer $key',
          'Content-Type': 'application/json',
        },
        body: jsonEncode({
          'model': 'gpt-3.5-turbo',
          'messages': [
            {
              'role': 'system',
              'content': '''You are $characterName, a character from Greek mythology.
Your description: $characterDescription
${characterPersonality != null ? 'Your personality: $characterPersonality\n' : ''}

You must always stay in character and respond according to your personality and background.
If asked about your name, identity, or background, respond based on your character description.
Never break character or acknowledge that you are an AI.
Keep your responses concise and engaging, matching your personality traits.''',
            },
            {
              'role': 'user',
              'content': message,
            },
          ],
          'temperature': 0.7,
          'max_tokens': 1000,
        }),
      );

      final DateTime endTime = DateTime.now();
      final Duration duration = endTime.difference(startTime);
      print('收到响应 - 时间: ${endTime.toIso8601String()}');
      print('请求耗时: ${duration.inSeconds}秒 ${duration.inMilliseconds % 1000}毫秒');
      print('响应状态码: ${response.statusCode}');
      print('响应内容: ${response.body}');

      if (response.statusCode == 200) {
        final data = jsonDecode(response.body);
        if (data['choices'] != null && 
            data['choices'].isNotEmpty && 
            data['choices'][0]['message'] != null) {
          final String content = data['choices'][0]['message']['content'];
          print('成功获取AI回复，内容长度: ${content.length}');
          return content;
        } else {
          print('响应格式无效: ${response.body}');
          throw Exception('Invalid response format');
        }
      } else {
        print('API错误 - 状态码: ${response.statusCode}');
        print('错误响应: ${response.body}');
        throw Exception('Failed to send message: ${response.statusCode}');
      }
    } catch (e, stackTrace) {
      final DateTime errorTime = DateTime.now();
      final Duration duration = errorTime.difference(startTime);
      print('发生错误 - 时间: ${errorTime.toIso8601String()}');
      print('错误耗时: ${duration.inSeconds}秒 ${duration.inMilliseconds % 1000}毫秒');
      print('错误类型: ${e.runtimeType}');
      print('错误信息: $e');
      print('堆栈跟踪: $stackTrace');
      throw Exception('Error sending message: $e');
    }
  }

  Future<List<ChatMessage>> getChatHistory(String characterId) async {
    print('获取聊天历史 - 角色ID: $characterId');
    final String? historyJson = _prefs.getString('$_storageKey$characterId');
    if (historyJson == null) {
      print('未找到聊天历史');
      return [];
    }
    
    try {
      final List<dynamic> history = jsonDecode(historyJson);
      print('成功获取聊天历史，消息数量: ${history.length}');
      return history.map((item) => ChatMessage.fromJson(item)).toList();
    } catch (e) {
      print('解析聊天历史失败: $e');
      return [];
    }
  }

  Future<void> saveChatHistory(String characterId, List<ChatMessage> messages) async {
    print('保存聊天历史 - 角色ID: $characterId, 消息数量: ${messages.length}');
    try {
      final String historyJson = jsonEncode(
        messages.map((message) => message.toJson()).toList(),
      );
      await _prefs.setString('$_storageKey$characterId', historyJson);
      print('聊天历史保存成功');
    } catch (e) {
      print('保存聊天历史失败: $e');
      throw Exception('Failed to save chat history: $e');
    }
  }

  Future<void> clearChatHistory(String characterId) async {
    print('清除聊天历史 - 角色ID: $characterId');
    try {
      await _prefs.remove('$_storageKey$characterId');
      print('聊天历史清除成功');
    } catch (e) {
      print('清除聊天历史失败: $e');
      throw Exception('Failed to clear chat history: $e');
    }
  }

  Future<List<ChatHistory>> getAllChatHistories() async {
    final List<ChatHistory> histories = [];
    final allKeys = _prefs.getKeys();
    
    for (final key in allKeys) {
      if (key.startsWith(_storageKey)) {
        final String? historyJson = _prefs.getString(key);
        if (historyJson != null) {
          try {
            final List<dynamic> messagesList = jsonDecode(historyJson);
            if (messagesList.isNotEmpty) {
              // 从第一条消息中获取角色信息
              final firstMessage = ChatMessage.fromJson(messagesList.first);
              final messages = messagesList
                  .map((msg) => ChatMessage.fromJson(msg))
                  .toList();
              
              final history = ChatHistory(
                characterId: key.replaceAll(_storageKey, ''),
                characterName: firstMessage.characterName ?? '',
                characterDescription: firstMessage.characterDescription ?? '',
                characterImageUrl: firstMessage.characterImageUrl ?? '',
                messages: messages,
              );
              histories.add(history);
            }
          } catch (e) {
            print('Error loading chat history for key $key: $e');
          }
        }
      }
    }
    
    // 按最后消息时间排序
    histories.sort((a, b) {
      final aTime = a.messages.isNotEmpty ? a.messages.last.timestamp : DateTime(0);
      final bTime = b.messages.isNotEmpty ? b.messages.last.timestamp : DateTime(0);
      return bTime.compareTo(aTime);
    });
    
    return histories;
  }
} 